package com.web.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.DynaActionForm;

import com.web.bdo.User;
import com.web.bdo.dao.UserDao;
import com.web.bdo.dao.util.UserDaoUtil;
import com.web.util.string.StringUtil;

public class LoginAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		ActionErrors errors = new ActionErrors();
		DynaActionForm loginForm = (DynaActionForm)form;
		
		String emailAddress = (String)loginForm.get("emailAddress");
		String password = (String)loginForm.get("password");
		
		if (StringUtil.isNullOrEmpty(emailAddress)) {
			errors.add("emailAddress", new ActionMessage("errors.login.required", "E-mail address"));
		}
		
		if (StringUtil.isNullOrEmpty(password)) {
			errors.add("password", new ActionMessage("errors.login.required", "Password"));
		}	
		
		if (!errors.isEmpty()) {
			saveMessages(request, errors);			
			return mapping.findForward("error");
		}
		
		User user = new User();
		user.setEmailAddress(emailAddress);
		user.setPassword(password);
		errors = loginToDatabase(user, request);
		
		if (!errors.isEmpty()) {
			saveMessages(request, errors);			
			return mapping.findForward("error");
		}
		
		request.getSession().setAttribute("user", user);
		request.getSession().setAttribute("logged", true);
		return mapping.findForward("success");
	}
	
	public ActionErrors loginToDatabase(User user, HttpServletRequest request) {
		
		ActionErrors errors = new ActionErrors();		
		errors = UserDaoUtil.login(user, request);		
		return errors;
	}
}
